package com.bookRecommend.provider;

import com.bookRecommend.model.User;
import org.apache.ibatis.builder.annotation.ProviderMethodResolver;
import org.apache.ibatis.jdbc.SQL;

public class UserProvider implements ProviderMethodResolver {

    public String selectByUser(User user) {
        SQL sql = new SQL().SELECT("*").FROM("user");
        String type = "select";
        return getSql(sql, user, type);
    }

    public String insertUser(User user) {
        SQL sql = new SQL().INSERT_INTO("user");
        String type = "insert";
        return getSql(sql, user, type);
    }

    public String updateUser(User user) {
        SQL sql = new SQL().UPDATE("user");
        String type = "update";
        return getSql(sql, user, type);
    }

    public String deleteUser(User user) {
        SQL sql = new SQL().DELETE_FROM("user");
        String type = "delete";
        return getSql(sql, user, type);
    }

    private String getSql(SQL sql, User user, String type) {

        if (user != null) {
            if (user.getId() != null) {
                switch (type) {
                    case "select" -> sql.WHERE("id like '%${id}%'");
                    case "update", "delete" -> sql.WHERE("id = #{id}");
                    case "insert" -> sql.VALUES("id", "#{id}");
                }
            }
            if (user.getUsername() != null) {
                switch (type) {
                    case "select" -> sql.WHERE("username like '%${username}%'");
                    case "update" -> sql.SET("username = #{username}");
                    case "delete" -> sql.WHERE("username = #{username}");
                    case "insert" -> sql.VALUES("username", "#{username}");
                }
            }
            if (user.getPassword() != null) {
                switch (type) {
                    case "select" -> sql.WHERE("password like '%${password}%'");
                    case "update" -> sql.SET("password = #{password}");
                    case "delete" -> sql.WHERE("password = #{password}");
                    case "insert" -> sql.VALUES("password", "#{password}");
                }
            }
            if (user.getEmail() != null) {
                switch (type) {
                    case "select" -> sql.WHERE("email like '%${email}%'");
                    case "update" -> sql.SET("email = #{email}");
                    case "delete" -> sql.WHERE("email = #{email}");
                    case "insert" -> sql.VALUES("email", "#{email}");
                }
            }
            if (user.getHeader() != null) {
                switch (type) {
                    case "update" -> sql.SET("header = #{header}");
                    case "delete" -> sql.WHERE("header = #{header}");
                    case "insert" -> sql.VALUES("header", "#{header}");
                }
            }
        }
        return sql.toString();
    }
}
